package com.neusoft.neuiotms.dcam.workflow.converter;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.WeixiuKJDTO;
import com.neusoft.neuiotms.dcam.workflow.model.WeixiuItemKJ;
import com.neusoft.neuiotms.dcam.workflow.model.WeixiuKJ;
import com.neusoft.neuiotms.dcam.workflow.repository.WeixiuItemKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.WeixiuKJRepository;

@Component
public class WeixiuKJConverter extends AbstractConverter<WeixiuKJ, WeixiuKJDTO> {

    @Autowired
    private WeixiuKJRepository weixiuKJRepository;
    @Autowired
    private WeixiuItemKJRepository weixiuItemKJRepository;
    @Autowired
    private WeixiuItemKJConverter weixiuItemKJConverter;

    @Override
    public WeixiuKJ toModel(final WeixiuKJDTO dto) {
        WeixiuKJ model;
        if (dto.isNew()) {
            model = new WeixiuKJ();
        } else {
            model = this.weixiuKJRepository.getOne(dto.getId());
        }

        final List<WeixiuItemKJ> list = model.getDetails().stream().collect(Collectors.toList());
        list.forEach(k -> {
            model.getDetails().remove(k);
            this.weixiuItemKJRepository.delete(k);
        });

        dto.getDetails().stream().map(k -> {
            final WeixiuItemKJ detail = this.weixiuItemKJConverter.toModel(k);
            detail.setMain(model);
            return detail;
        }).filter(s -> null != s).forEach(model.getDetails()::add);

        model.setWorkOrderNum(dto.getWorkOrderNum());
        model.setTaskId(dto.getTaskId());
        model.setTitle(dto.getTitle());
        model.setRemark(dto.getRemark());
        model.setCreateUser(dto.getCreateUser());
        model.setCreateUserName(dto.getCreateUserName());
        model.setComprehensive(dto.getComprehensive());

        return model;
    }

    @Override
    public WeixiuKJDTO toDTO(final WeixiuKJ model, final boolean forListView) {
        final WeixiuKJDTO dto = new WeixiuKJDTO();
        dto.setId(model.getId());
        dto.setWorkOrderNum(model.getWorkOrderNum());
        dto.setTaskId(model.getTaskId());
        dto.setTitle(model.getTitle());
        dto.setRemark(model.getRemark());
        dto.setCreateUser(model.getCreateUser());
        dto.setCreateUserName(model.getCreateUserName());
        dto.setComprehensive(model.getComprehensive());
        model.getDetails().stream().map(l -> this.weixiuItemKJConverter.toDTO(l))
                .forEach(dto.getDetails()::add);
        return dto;
    }

}
